// 页面的数据源
import Vue from "vue"
// 和网络交互相关的参数
let params = {
  //搜索条件
  deliver: {
    waybill: '',
    deliveryCompany: '',
  },
  exportOrder: {
    id: '',
    serialNumber: '',
    userName: ''
  },
  selectedOrders: [],
  subRefundOrderItem : {
    id:'',
    serialNumber: '',
    number:0,
    refundPayment:0,
    itemPayment:0,
    itemNumber:0,
    state : 0
  },
  modifyInnerNote:{
    id:"",
    serialNumber:"",
    innerNote:""
  },
  modifyImportantNote:{
    orderIds:[],
    importantNote:"",
  },
  refusePayment:{
    poundage: 0
  },
  exportInvoice: {
    orderId: "",
    companyName: "",
    selectedOrderItemStates: []
  },
  refund:{
    note:'',
    shippingFee:0
  },
  confirmOffline: {
    orderId:"",
    serialNumber: "",
    payway: 0,
    fixedPoundage: 0,
    ratePoundage: 0,
    rate: 0
  }
};
//页面状态相关
let data = {
  loginTypeDict: [],
  orderItemDict: [],
  orderDetail: { },
  selectRecord: [],
  discounts: [],
  orderPaymentRecords: [],
  productSupplyList:[],
};


let status = {
  //显示order的 modal
  modalDetail: {
    isShow: false,
  },
  modalRecord: {
    title: "",
    info:{
      productCode:"",
      productColor:"",
      productSize:""
    },
    recordType: 0, //记录类型。1：订单；2：包裹；3：订单项
    isShow: false,
  },
  //查看图片
  modalImage: {
    isShow: false,
    url: ''
  },
  //发货
  modalDeliver: {
    isShow: false,
    title: "整单发货",
    isLoading: true,
    params: {
      type: 0,
      selectedOrderItem: [],
      packageId: '',
      orginalWaybill: ''
    }
  },
  rules: {
    waybill: [
      {required: true, message: '运单号不能为空', trigger: 'blur'}
    ],
    deliveryCompany: [
      {required: true, message: '请选择快递公司', trigger: 'change'}
    ],
  },
  modalTracking:{
    isShow:false,
    title: "跟踪包裹",
    isLoading: true,
    info:[]
  },
  modalDiscount:{
    isShow:false,
    title:"订单折扣明细"
  },
  modalConfirmOrderShow : false,
  modalSubRefund:{ //拆分缺货产品
    isShow:false,
    refundReadonly:false
  },
  modalRefundItems:{ //退款
    isShow:false,
    type:1
  },
  modalAction: {
    isShow: false,
    isLoading: false,
    title: '',
    content: '',
    type: 0,//0:备货1出库
    order: {
      id: ''
    }
  },
  modalInnerNote:{ //修改运营备注
    isShow:false
  },
  modalPaymentRecordShow:false,//订单款项记录,
  modalSupply:{ //产品货源弹出框
    isShow:false
  },
  modalRefusePayment:{ //设置用户拒付弹出框
    isShow:false
  },
  modalImportantNote: {
    isShow:false
  },
  modalExportInvoice: {
    isShow: false,
  },
  refundRules: {
    note: [
      {required: true, message: '退款原因不能为空', trigger: 'blur'}
    ],
    shippingFee:[
      {
        required: true,
        validator:(rule, value, callback) => {
          if(status.modalRefundItems.type!=3){
            callback()
          }
          if (value== ''||parseInt(value)<=0) {
            return callback(new Error('运费必须大于0'))
          } else if (value>data.orderDetail.postage) {
            return callback(new Error('运费必须小于总运费'))
          } else {
            callback()
          }
        }, trigger: 'blur'}
    ]
  },
  modalConfirmOffline:{ //确认线下收款
    isShow:false
  },
  confirmOfflineRules: {
    payway: [
      {required: true, message: '必须选择支付方式', trigger: 'blur, change'}
    ],
    fixedPoundage: [
      {
        validator:(rule, value, callback) => {
          if (value < 0) {
            return callback(new Error('必须填写固定手续费'))
          } else {
            callback()
          }
        }, trigger: 'blur'}
    ],
    ratePoundage:[
      {
        validator:(rule, value, callback) => {
          if(status.modalConfirmOffline.ratePoundage < 0 && status.modalConfirmOffline.rate < 0){
            return callback(new Error('比例手续费或者手续费比例至少需要填写一个。'));
          } else {
            callback();
          }
        }, trigger: 'blur'}
    ]
  }
};
//订单项列表
let tableTitles ={
  tableOrderDetail:function(self){
    return[{
      type: 'selection',
      align: 'center',
      width: 60,
    },
    {
      title: '产品编码',
      key: 'productCode',
      align: 'center',
      minWidth:130
    },
    {
      title: '色卡',
      key: 'color',
      align: 'center',
      minWidth:130
    },
    {
      title: '尺码',
      key: 'sizeName',
      align: 'center',
      minWidth:130
    },
    {
      title: '数量',
      key: 'amount',
      align: 'center',
      minWidth:90
    },
    {
      title: '折扣金额($)',
      key: "itemDiscount",
      align: 'center',
      minWidth:130,
      render: (h, params) => {
        let discount = (params.row.actualPrice * params.row.amount - params.row.actualPayment).toFixed(3);
        if(discount <= 0){ //没有折扣时显示0，有折扣显示折扣值并作a链接
          return h('div', 0);
        } else {
          return h('a',
            {
              attrs:{
                href:'#'
              },
              on: {
                click: () => {
                  self.showItemDiscounts(params.row.id);
                }
              }
            }, discount);
        }
      }
      },
      {
        title: '订单项状态',
        key: 'state',
        align: 'center',
        width: 130,
        render: (h, params) => {
          return h('div', self.orderItemStateDict.filter(item => item.value == params.row.state)[0].name);
        }
      },
      {
        title: '操作',
        align: 'center',
        width: 250,
        render: (h, params) => {
          let status = false;
          let rowState = params.row.state;
          if(!self.$authority("ORDER-1-214")){
            status = false;
          } else if(rowState == 112 || rowState == 114 || rowState == 120){//} || rowState == 140){
            //只能对已出库、已发货、已确认收货的订单项执行部分退款操作
            status = true;
          }
          return h('div',[status? h('Button',
            {
              props: {type: 'primary', size: 'small', icon: "md-create"},
              style: {marginRight: '10px'},
              on: {
                click: () => {
                  self.params.subRefundOrderItem.id = params.row.id;
                  self.params.subRefundOrderItem.serialNumber = params.row.serialNumber;
                  self.params.subRefundOrderItem.itemPayment = params.row.actualPayment;
                  self.params.subRefundOrderItem.itemNumber = params.row.amount;
                  self.params.subRefundOrderItem.state = params.row.state;
                  self.params.subRefundOrderItem.number = 0;
                  self.params.subRefundOrderItem.refundPayment = 0;
                  self.status.modalSubRefund.isShow = true;
                  self.status.modalSubRefund.refundReadonly = false;
                }
              }
            }, '缺货拆分') : h('div'),
            h('Button',
              {
                props: {type: 'default', size: 'small', icon: "md-information-circle"},
                style: {marginRight: '10px'},
                on: {
                  click: () => {
                    data.selectRecord.length = 0;
                    self.showItemRecord(params.row);
                  }
                }
              }, '查看记录')]);
        }
      }]
  },
  tableRecordDetail:[
    {
      type: 'index',
      title: '#',
      align: 'center',
      width: 60
    },
    {
      title: '操作后状态',
      key: 'stateName',
      minWidth:150
    },
    {
      title: '操作人',
      key: 'operator',
      align: 'center',
      width: 120
    },
    {
      title: '操作时间',
      key: 'createtime',
      align: 'center',
      width: 150,
      render: (h, params) => {
        return h('div', Vue.prototype.$tiyBJTime(params.row.createtime));
      }
    }
  ],
  tableDiscount:[
    {
      type: 'index',
      title: '序号',
      align: 'center',
    },
    {
      title: '折扣类型',
      key: 'type',
      render: (h, params) => {
        let type;
        switch (params.row.discountType) {
          case 1:
            type = "订单满减";
            break;
          case 4:
            type = "优惠券";
            break;
          default:
            type = "";
            break;
        }
        return h('div', type);
      }
    },
    {
      title: '折扣名称',
      key: 'content'
    },
    {
      title: '折扣金额($)',
      key: 'amount',
    }
  ],
  tablePaymentRecord:function(self) {
    return [
      {
        type: 'index',
        title: '序号',
        align: 'center',
        width: 80
      },
      {
        title: '时间',
        key: 'createtime',
        align: 'center',
        width: 180,
        render: (h, params) => {
          return h('div', self.$tiyBJTime(params.row.createtime));
        }
      },
      {
        title: '收款/退款',
        width: 120,
        render: (h, params) => {
          return h('div', params.row.payOrRefund ? '收款' : '退款');
        }
      },
      {
        title: '发生金额（$）',
        key: 'actualPayment',
        minWidth:100,
        render: (h, params) => {
          return h('div', Math.abs(params.row.actualPayment));
        }
      },
      {
        title: '运费（$）',
        key: 'postage',
        minWidth:150,
        render: (h, params) => {
          return h('div', Math.abs(params.row.postage));
        }
      },
      {
        title: '原因',
        minWidth:200,
        render: (h, params) => {
          if (params.row.payOrRefund) {
            return h('div', '订单支付');
          }
          let reason = "";
          self.refundReasonDict.forEach(function(item){
            if(item.value == params.row.refundReason){
              reason = item.name;
              return;
            }
          });
          if(reason){
            return h('div', reason);
          }
        }
      }
    ]},
}

let productSupplyTable = function (self) {
  return [
    {
      type: 'index',
      title: '#',
      width: 60,
      key: 'index',
      fixed: 'left',
      align: 'center',
    },
    {
      title: '标题',
      key: 'name',
      width:  240,
      align: 'center'
    },
    {
      title: '采购渠道',
      key: 'source',
      width:  100,
      align: 'center',
      render: (h, params) => {
        let soureName;

        return (<span>{soureName}</span>);
      }
    },
    {
      title: '采购链接',
      key: 'url',
      width: 220,
      align: 'center',
      render: (h, params) => {
        if (params.row.url.startsWith("http")) {
          return (
            <div>
              <a style="padding:6px;font-size:13px" target="_blank" href={params.row.url}>{params.row.url}</a>
            </div>
          );
        } else {
          return (
            <span></span>
          );
        }
      }
    },
    {
      title: '参考价格',
      key: 'referencePrice',
      width: 100,
    },
    {
      title: '创建时间',
      key: 'createtime',
      width: 180,
      align: 'center',
      render: (h, params) => {
        let date = new Date(params.row.createtime);
        return h('div', self.$tiyBJTime(params.row.createtime));
      }
    }
  ];
};

export default  {
  tData: data,
  tStatus:status,
  tParams: params,
  tableTitles:tableTitles,
  productSupplyTable:productSupplyTable
};
